package mode.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * cglib动态代理
 *
 * @author xjx
 * @date 2023/7/19 16:05
 */
public class NginxInvocationHandler implements MethodInterceptor {

    /**
     * 新浪服务器列表
     */
    private static final List<String> SINA_SERVER_ADDRESSES = Arrays.asList("192.168.1.1", "192.168.1.2", "192.168.1.3");

    private Object target;

    public Object getProxy(Object target) {
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        String remoteIp = UUID.randomUUID().toString();
        int index = Math.abs(remoteIp.hashCode()) % SINA_SERVER_ADDRESSES.size();
        String realSinaIp = SINA_SERVER_ADDRESSES.get(index);

        StringBuilder sb = new StringBuilder();
        sb.append("【页面标题：");
        //调用实际被代理的方法
        sb.append(methodProxy.invokeSuper(o, objects));
        sb.append("】,【来源Ip：");
        sb.append(realSinaIp);
        sb.append("】");
        return sb.toString();
    }
}
